<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button flex felx_align">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
        <div class="guidetext" @click="imgShow = true"><i class="iconfont iconiconfontwenhao1 guide"></i>操作指引</div>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <!-- <el-option label="主页" value="1"></el-option> -->
              <el-option label="批次" value="2"></el-option>
              <el-option label="归属" value="3"></el-option>
              <!-- <el-option label="书签" value="4"></el-option> -->
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 设备归属管理table -->
    <el-table stripe style="width: 100%" :data="tableData" :key="key" border fit highlight-current-row ref="tableDataRef" max-height="545">
      <el-table-column v-if="colData[0].istrue" min-width="100" align="center" prop="username" label="归属"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="140" align="center" prop="batch" label="批次"></el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="180" align="center" prop="home_page" label="浏览器主页"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="180" align="center" prop="label_page" label="书签管控设置"></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="140" align="center" prop="create_time" label="更新时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column min-width="150" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryIdLabel(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="deleteShow(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize"></el-pagination>
    </div>
    <!-- 隐藏 -->
    <!-- 添加dialog表单 -->
    <div>
      <el-dialog :title="editSubjects ? ' 浏览器书签设置功能' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="45%">
        <el-form :model="addForm" ref="ruleForm" :rules="rules" class="diolog_adapt">
          <el-form-item label="批次:" label-width="140px" prop="batch">
            <el-select v-model="addForm.batch" placeholder="没有选中任何项" multiple class="add_select">
              <el-option v-for="item in lotoptions" :key="item.id" :label="item.batch" :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设置浏览器主页" label-width="140px" prop="home_page">
            <el-input v-model="addForm.home_page" class="add_select" placeholder="请输入完整的网址"></el-input>
          </el-form-item>
          <!-- :rules="{ validator: validateUsername, trigger: 'blur' }" -->
          <el-form-item label-width="140px" label="添加浏览器标签:" v-for="(domain, index) in addForm.label_page" :key="domain.key" :rules="{ required: true, message: '请输入浏览器标签', trigger: 'blur' }"
            :prop="'label_page.' + index + '.value'">
            <div class="addPut">
              <el-input v-model="domain.value" placeholder="请输入完整的网址"></el-input>
              <el-button class="dlePut btnLocation" round size="mini" icon="el-icon-delete" @click.prevent="removeDomain(domain)"></el-button>
            </div>
          </el-form-item>
          <el-form-item label-width="140px">
            <el-button type="primary" @click="addDomain" size="mini">添加书签</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
          <el-button v-if="editSubjects" type="primary" @click="getaddLabel('ruleForm')" size="mini">确 定</el-button>
          <el-button v-else type="primary" @click="geteditLabel('ruleForm')" size="mini">编辑</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 模板操作图片弹窗 -->
    <div class="component" v-if="imgShow">
      <div class="mbImg"><img src="@/assets/images/snLlq.png" alt=""></div>
      <div class="masking" @click="imgShow = false"></div>
    </div>
    <!-- 删除弹窗 -->
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import { queryLabelAll, queryIdLabel, editLabel, addLabel, deleteLabel } from "@/api/deployment.js";
import deleteDialog from "@/components/deleteDialog";
import { getBatchTwo } from "@/api/equipment.js";
import tableMini from '@/utils/tableMini.js'
export default {
  mixins: [tableMini],
  components: { dynamicTable, deleteDialog },
  data() {
    var validateUsernames = (rule, value, callback) => {
      var reg = /^(?!http).*/
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的网址,请勿以https://或http://开头'))
      } else {
        callback()
      }
    }
    return {
      validateUsername: (rule, value, callback) => {
        var reg = /^(?!http).*/
        if (!reg.test(value)) {
          return callback(new Error('请输入正确的网址,请勿以https://或http://开头'))
        } else {
          callback()
        }
      },
      checkboxVal: ["归属", "批次", "浏览器主页", "书签管控设置", "更新时间"],
      select: "2", //搜索条件
      tableData: [],
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制 
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      //批次下拉选择
      lotoptions: [],
      //添加表单
      addForm: { home_page: "", batch: "", label_page: [], },
      rules: { home_page: [{ required: true, message: '请输入浏览器主页', trigger: 'blur' }], batch: [{ required: true, message: "请选择批次", trigger: "blur" }] },
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), home_page: undefined, batch: undefined, username: undefined, label_page: undefined, sort: '' },
      imgShow: false
    }
  },
  created() {
    this.getTabularData()
    this.getBatchTwos()
  },
  methods: {
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteLabel(params).then(res => {
        this.$message.success(res.msg)
        this.getTabularData()
      })
    },
    //添加书签信息
    getaddLabel(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addForm.label_page = this.addForm.label_page.map(item => item.value.toLowerCase()).toString()
          addForm.home_page = this.addForm.home_page
          addLabel(addForm).then(res => {
            this.$message.success(res.msg)
            this.getTabularData()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false;
        }
      });
    },
    //编辑书签信息
    geteditLabel(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addForm.batch = this.addForm.batch.toString()
          addForm.id = this.subjectId
          addForm.label_page = this.addForm.label_page.map(item => item.value.toLowerCase()).toString()
          addForm.home_page = this.addForm.home_page
          editLabel(addForm).then(res => {
            this.dialogFormVisible = false
            this.$message.success(res.msg)
            this.getTabularData()
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //查询书签信息
    getqueryIdLabel(id) {
      this.editSubjects = false
      this.subjectId = id
      queryIdLabel({ id: id }).then(res => {
        this.dialogFormVisible = true
        let data = res.data
        this.addForm.batch = data.batch.split(',')
        this.addForm.home_page = data.home_page
        // this.addForm.label_page = data.label_page.split(',').map(item => { return { 'value': item.replace(/^https?:\/\//, '') } })
        this.addForm.label_page = data.label_page.split(',').map(item => { return { 'value': item } })
      }).catch(err => { })
    },
    getTabularData() {
      queryLabelAll(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    //表单动态添加input
    removeDomain(item) {
      var index = this.addForm.label_page.indexOf(item)
      if (index !== -1) {
        this.addForm.label_page.splice(index, 1)
      }
    },
    addDomain() {
      if (this.addForm.label_page.length == 9) return this.$message({ type: 'warning', message: '需要定义书签不能超过9条' })
      this.addForm.label_page.push({ value: '', key: Date.now() });
    },
    //搜索,1：主页，2:批次
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.home_page = this.searchTable
          break;
        case '2':
          let search = this.lotoptions.filter(key => key.batch == this.searchTable).map(item => item.id)[0]
          this.listQuery.batch = search ? search : this.searchTable
          break;
        case '3':
          this.listQuery.username = this.searchTable
          break;
        case '4':
          this.listQuery.label_page = this.searchTable
          break;
      }
      this.getTabularData();
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm = {
          home_page: "",
          batch: "",
          label_page: [],
        }
      })
    }
  }
}
</script>

<style scoped>
/deep/ .el-dialog__header {
  transform-origin: 50% 100%;
  border-bottom: 0.5px solid #e9e9e9;
}
</style>